import redis.asyncio as redis

redis_server = None


async def scan_tool(pattern: str = "*", count: int = 100, cursor: int = 0) -> str:
    """
    Scan keys in Redis matching a pattern without blocking the server.
    """
    if redis_server is None:
        return "Redis server not initialized"

    try:
        client = await redis_server.get_connection()  # type: ignore

        next_cursor, keys = await client.scan(cursor=cursor, match=pattern, count=count)

        if keys:
            keys_list = ", ".join(keys)
            message = f"{keys_list}"

            # if next_cursor != 0:
            #     message += f" (more keys, use cursor={next_cursor})"

            return message
        else:
            if next_cursor != 0:
                return f"notfound, use cursor={next_cursor} continue"
            else:
                return f"notfound '{pattern}'"

    except redis.RedisError as e:
        return f"Redis Error: {str(e)}"
    except Exception as e:
        return f"scan error: {str(e)}"
